<?php

if( !defined( 'MEDIAWIKI' ) ) {
   echo( "This file is an extension to the MediaWiki software and cannot be used standalone.\n" );
   die( 1 );
}

require_once("DatabaseFunctions.php");

$wgExtensionCredits['soundsharewiki'][] = array(
   'version'     => '0.0.1',
   'name'        => 'SoundshareWiki',
   'author'      => 'MP2P Technologies',
   'email'       => 'leo at mp2p dot net',
   'url'         => '',
   'description' => 'Alter some characteristics in wiki entries display and editing process.'
);
$wgExtensionFunctions[] = 'swParserFunctionInit';

#install extension hook
$wgHooks['BeforePageDisplay'][] = 'swBeforeDisplay';
$wgHooks['OutputPageBeforeHTML'][] = 'swBeforeHTML';
$wgHooks['EditPage::showEditForm:fields'][] = 'swEditFields';
$wgHooks['ArticleSave'][] = 'swArticleSave';
//$wgHooks['ArticleAfterFetchContent'][] = 'swAfterFetchContent';
$wgHooks['LanguageGetMagic'][]       = 'swParserFunctionMagic';
$wgHooks['ArticleFromTitle'][] = 'swArticleFromTitle';
//$wgHooks['APIEditBeforeSave'][] = 'swAPIEditBeforeSave';

/*function swAPIEditBeforeSave( &$EditPage, $text, &$resultArr ) 
{
	echo "<pre>";
	var_dump($EditPage);
echo "<hr>";
	var_dump($text);
echo "<hr>";
	var_dump($resultArr);
	echo "</pre>";
	die(-1);
	return true;
}*/

function swArticleFromTitle(&$title, &$article) {
	global $wgTitle;
	$wgTitle->getDisplayInfo();
	return true;
}

function swParserFunctionInit() {
        global $wgParser;
	$wgParser->setFunctionHook( 'release', 'swReleaseParser', SFH_NO_HASH );
	$wgParser->setFunctionHook( 'artist', 'swArtistParser', SFH_NO_HASH );
	$wgParser->setFunctionHook( 'song', 'swSongParser', SFH_NO_HASH );
}
 
function swParserFunctionMagic( &$magicWords, $langCode ) {
        $magicWords['release'] = array( 0, 'release', wfMsg('release') );
        $magicWords['song'] = array( 0, 'song', wfMsg('song') );
        $magicWords['artist'] = array( 0, 'artist', wfMsg('artist') );
        return true;
}
 
function swReleaseParser( &$parser, $param1, $param2) {
	global $wgOut;
	$param1 = str_replace('/', ' ', $param1);
	$param2 = str_replace('/', ' ', $param2);

	$title = SoundshareTitle::newFromText("$param1/$param2", NS_RELEASE);
	$class = $title->isKnown()?"":" class='new'";
	$parser->mOutput->addLink($title);
        return $parser->insertStripItem("<a href='".htmlspecialchars($title->getLocalUrl(), ENT_QUOTES)."' $class title='$param1 - $param2'>$param2</a>", $parser->mStripState );
}
 
function swSongParser( &$parser, $param1, $param2) {
	$param1 = str_replace('/', ' ', $param1);
	$param2 = str_replace('/', ' ', $param2);

	$title = SoundshareTitle::newFromText("$param1/$param2", NS_SONG);
	$class = $title->isKnown()?"":" class='new'";
	$parser->mOutput->addLink($title);
        return $parser->insertStripItem("<a href='".htmlspecialchars($title->getLocalUrl(), ENT_QUOTES)."' $class title='$param1 - $param2'>$param2</a>", $parser->mStripState );
}
 
function swArtistParser( &$parser, $param1) {
	$param1 = str_replace('/', ' ', $param1);

	$title = SoundshareTitle::newFromText($param1, NS_ARTIST);
	$class = $title->isKnown()?"":" class='new'";
	$parser->mOutput->addLink($title);
        
        return $parser->insertStripItem("<a href='".htmlspecialchars($title->getLocalUrl(), ENT_QUOTES)."' $class title='$param1'>$param1</a>", $parser->mStripState );
}
/*
function swAfterFetchContent( &$article, &$content ) 
{
	global $wgRequest, $wgTitle, $wgOut, $wgParser;
	switch ($wgTitle->mNamespace)
	{
		case NS_ARTIST:
		case NS_RELEASE:
		case NS_SONG:
			if ($wgRequest->getVal( 'action' ) == 'edit' && $content!='')
			{
				$blocks = explode("\n", $content, 2);
				$content = $blocks[1];
				
			}
			break;
	}
	return true;
}*/

function swBeforeHTML( &$out, &$text )
{
	global $wgTitle;
	$title_type = "h1";
	if ($wgTitle->mNamespace==NS_CATEGORY)
		$text = "";
	else
 	{
		if ($out->isArticle()) {
			$text = "<!--LAY-H-->$text<!--LAY-W-->";
			$out->mHasHeader = true;
		}
	}
	return true;
}

function swBeforeDisplay( &$out, &$sk )
{
	global $wgTitle, $wgRequest;
	$action = $wgRequest->getText('action', '');
	switch ($wgTitle->mNamespace)
	{
		case NS_CATEGORY:
			$out->mMainSearch = true;
			$out->mType = $wgTitle->getDisplay();
			$out->mHasHeader = true;
			break;
		case NS_ARTIST:
			$out->mType = wfMsg('artist');
			if ($action!='edit') $out->mWikiHeader = "<h1>".$wgTitle->getDisplay()."</h1>";
			$out->setPageTitle($wgTitle->getDisplay());
			break;
		case NS_SONG:
			$out->mType = wfMsg('song');
			if ($action!='edit') $out->mWikiHeader = "<h2>".$wgTitle->getDisplay()."</h2>";
			$out->setPageTitle($wgTitle->getDisplay());
			break;
		case NS_RELEASE:
			$out->mType = wfMsg('album');
			if ($action!='edit') $out->mWikiHeader = "<h1>".$wgTitle->getDisplay()."</h1>";
			$out->setPageTitle($wgTitle->getDisplay());
			break;
		default:
			$out->mType = $out->mDefaultTitle;
			$out->mWikiHeader = "<h1>".$wgTitle->getDisplay()."</h1>";
			break;
	}
	
	return true;
}

function swEditFields(&$editPage, &$output)
{
	global $wgTitle, $wgOut;

	switch ($wgTitle->mNamespace)
	{
		case NS_ARTIST:
			$prefix = "";
			$sql = "select Artist as Display, sum(countTagsOk+weight) textWeight from ss_tags where artistKey = '{$wgTitle->mArtistKey}' group by BINARY artist order by textWeight desc limit 5;";
			$current = coalesce($wgTitle->mArtistDisplay, $wgTitle->mArtist);
			break;
		case NS_SONG:
			$prefix = htmlspecialchars(coalesce($wgTitle->mArtistDisplay, $wgTitle->mArtist), ENT_QUOTES)." - ";
			$current = coalesce($wgTitle->mNoArtistDisplay, $wgTitle->mNoArtist);
			$sql = "select Title as Display, sum(countTagsOk+weight) textWeight from ss_tags where artistKey = '{$wgTitle->mArtistKey}' and titleKey='{$wgTitle->mNoArtistKey}' group by BINARY artist, BINARY title order by textWeight desc limit 5;";
			break;
		case NS_RELEASE:
			$prefix = htmlspecialchars(coalesce($wgTitle->mArtistDisplay, $wgTitle->mArtist), ENT_QUOTES)." - ";
			$current = coalesce($wgTitle->mNoArtistDisplay, $wgTitle->mNoArtist);
			$sql = "select Album as Display, sum(countTagsOk+weight) textWeight from ss_tags where artistKey = '{$wgTitle->mArtistKey}' and albumKey='{$wgTitle->mNoArtistKey}' group by BINARY artist, BINARY album order by textWeight desc limit 5;";
			break;
	}

	if ($sql!='')
	{
		$dbr = wfGetDB( DB_SLAVE );
               	$res = $dbr->query($sql);
		// if has results to show...
		$count = 0;
		if ($row=$dbr->fetchObject($res))
		{
			$lastWeight = $row->textWeight;
			do {
				if ($lastWeight>$row->textWeight*5) break;
				$html = htmlspecialchars($row->Display, ENT_QUOTES);
				$selected = strcmp($current, $row->Display)==0?" selected='selected'":"";
				$combo .= "<option value='$html'$selected>$prefix$html</option>";
				$lastWeight = $row->textWeight;
				$count++;
			} while ($row=$dbr->fetchObject($res));
			if ($count<2) {
				$combo=false;
				$html = htmlspecialchars($current, ENT_QUOTES);
			}
		}
		$dbr->freeResult($res);
	}
	
	if ($combo)
		$output->addHTML("<select class='display-name-selector' name='display-name'>$combo</select></span>");
	else
		$output->addHTML("<span class='display-name-selector'>$prefix$current<input type='hidden' name='display-name' value='$html'/></span>");

	return true;
}

function swArticleSave( &$article, &$user, &$text, &$summary, $minor, $watch, $sectionanchor, &$flags ) 
{
	global $wgRequest, $wgTitle;
	switch ($wgTitle->mNamespace)
	{		
		case NS_ARTIST:
			$norm = $wgTitle->mArtistKey;
		case NS_RELEASE:
		case NS_SONG:
			$display = $wgRequest->getText('display-name', '');
			if ($display=='') $display = ($wgTitle->mNamespace==NS_ARTIST)?$wgTitle->mArtist:$wgTitle->mNoArtist;
			if ($norm=='') $norm = $wgTitle->mNoArtistKey;
			// check if its a valid display name
			if( strcmp(normalize($display), $norm )==0 )
			{
				$fields = array('type'=>$wgTitle->mNamespace, 'artistKey'=>$wgTitle->mArtistKey, 'noArtistKey'=>coalesce($wgTitle->mNoArtistKey,''), 'display'=>$display);
 				$dbr = wfGetDB( DB_SLAVE );
		 		$dbr->replace('`ss_tags_info`', null, $fields, 'ss_tags_info update');
			}
			break;
	}
	return true;
}

